package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.http.HttpClient;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author 龙培
 * @Create 2025/3/5 20:04
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    private static final String WEIXIN_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    @Override
    public User wxlogin(UserLoginDTO userLoginDTO){
        //获取openid
        String openid = getOpenid(userLoginDTO);
        //判断是否为空
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //查询数据库是否存在该用户
        User user = userMapper.selectByOpenId(openid);
        if(user == null){
            //不存在，则新增用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        return user;
    }
    private String getOpenid(UserLoginDTO userLoginDTO){
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        //发送请求获取openid
        String responseStr = HttpClientUtil.doGet(WEIXIN_LOGIN,paramMap);
        JSONObject jsonObject = JSON.parseObject(responseStr);
        return jsonObject.getString("openid");
    }
}
